package com.imooc.controller;

import com.imooc.common.config.ProjectUrlConfig;
import com.imooc.common.constant.CommonConstant;
import com.imooc.common.enums.ResultEnum;
import com.imooc.common.utils.CookieUtil;
import com.imooc.dataobject.SellerInfo;
import com.imooc.service.SellerInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Controller
public class SellerUserController {

    @Autowired
    SellerInfoService sellerInfoService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProjectUrlConfig config;

    @RequestMapping("/login")
    public ModelAndView login(@RequestParam("openid") String openid, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();

        // 比对openid
        SellerInfo sellerInfo = sellerInfoService.findSellerInfoByOpenid(openid);
        if (sellerInfo == null) {
            log.error(ResultEnum.LOGIN_FAIL.getMessage());
            params.put("msg", ResultEnum.LOGIN_FAIL.getMessage());
            params.put("url", "/sell/seller/order/list");
            return new ModelAndView("common/error", params);
        }

        // 将token存入redis
        String token = UUID.randomUUID().toString();
        Integer expire = CommonConstant.EXPIRE;

        redisTemplate.opsForValue().
                set(String.format(CommonConstant.REDIS_TOKEN_PREFIX, token), openid, expire, TimeUnit.SECONDS);

        // token设置到cookie
        CookieUtil.setCookie(response, CommonConstant.TOKEN, token, expire);

        return new ModelAndView("redirect:" + config.getSell() + "/sell/seller/order/list");
    }

    /**
     * 登出
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/logout")
    public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        Cookie cookie = CookieUtil.getCookie(request, CommonConstant.TOKEN);
        if (cookie != null) {
            redisTemplate.opsForValue().getOperations().delete(String.format(CommonConstant.REDIS_TOKEN_PREFIX, cookie.getValue()));
            CookieUtil.setCookie(response, CommonConstant.TOKEN, null, 0);
        }

        params.put("msg", "登出成功");
        params.put("url", "/sell/seller/order/list");
        return new ModelAndView("common/success", params);
    }
}
